﻿package net.wangit.dev.unit;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.ColumnRowUtil;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.UnitVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class SaveUnitAction extends DomainAction {

	private static Version version = new UnitVersion();

	public SaveUnitAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newUnitId = ac.getRequestParameter("u.uid");
		if (!Checker.isEmpty(newUnitId))
			newUnitId = StringUtil.clearSpace(newUnitId.toLowerCase());
		format(ac, newUnitId);
		super.doAction(db, ac);
		ac.setSessionAttribute(UnitUI.KEY, newUnitId);
		String oldUnitId = ac.getRequestParameter("u.uid.k");
		if (!Checker.isEmpty(oldUnitId) && oldUnitId.equals(newUnitId))
			ac.getActionResult().setScript(null);
		UnitCacheUtil.clearAll(domain, oldUnitId);
		UnitReferenceUtil.update(db, domain, oldUnitId, newUnitId);
		VersionUtil.saveVersion(ac, version, domain, newUnitId);
	}

	private void format(ActionContext ac, String unitId) {
		List<Table> tables = ac.getTables();
		for (int i = 0; i < tables.size(); i++) {
			Table table = tables.get(i);
			String tableName = table.getTableName();
			if ("UNIT".equals(tableName))
				formatUnit(ac, table.getRows(), unitId);
			else if ("ELEMENT".equals(tableName))
				formatElement(table.getRows(), unitId);
		}

	}

	private void formatUnit(ActionContext ac, List<ColumnRow> rows,
			String unitId) {
		if (rows.size() > 0) {
			ColumnRow cRow = rows.get(0);
			cRow.set("uid", unitId);
			ColumnRowUtil.clearSpace(cRow, "d");
			ColumnRowUtil.clearSpace(cRow, "rc");
			ColumnRowUtil.clearSpace(cRow, "cc");
			ColumnRowUtil.clearSpace(cRow, "ui");
			ColumnRowUtil.clearSpace(cRow, "ut");
			ColumnRowUtil.clearSpace(cRow, "pi");
			ColumnRowUtil.clearSpace(cRow, "pt");
			ColumnRowUtil.clearSpace(cRow, "pcp");
			ColumnRowUtil.clearSpace(cRow, "phjp");
			ColumnRowUtil.clearSpace(cRow, "ptjp");
			LockUtil.setFields(ac, cRow, "u");
		}
	}

	private void formatElement(List<ColumnRow> rows, String unitId) {
		for (int i = 0; i < rows.size(); i++) {
			ColumnRow cRow = rows.get(i);
			cRow.set("uid", unitId);
			String elementId = cRow.get("eid");
			if (!Checker.isEmpty(elementId)) {
				elementId = StringUtil.clearSpace(elementId.toLowerCase());
				cRow.set("eid", elementId);
			}
			ColumnRowUtil.clearSpace(cRow, "ac");
			ColumnRowUtil.clearSpace(cRow, "ad");
		}

	}

}
